package com.crazymakercircle.iodemo.socketdemos;

import com.crazymakercircle.util.IOUtil;
import com.crazymakercircle.util.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;


/**
 * 文件传输Client端
 * Created by 尼恩@ 疯创客圈
 *
 * @author admin
 */

public class NioSendClient {

    private Charset charset = Charset.forName("UTF-8");

    public static void main(String[] args) throws IOException {
        Path path = Paths.get("d:/1.txt");
        File file = path.toFile();
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.socket().connect(new InetSocketAddress("127.0.0.1", 8888));
        socketChannel.configureBlocking(false);
        Logger.debug("Client 成功连接服务端");

        while (!socketChannel.finishConnect()) {
            //不断的自旋、等待，或者做一些其他的事情
        }
        //发送文件名称
        NioSendClient client = new NioSendClient();
        ByteBuffer fileName = client.charset.encode(path.getFileName().toString());
        socketChannel.write(fileName);

        //发送文件长度
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.putLong(file.length());
        buffer.flip();
        socketChannel.write(buffer);
        buffer.clear();
        //发送文件内容
        FileChannel fileChannel = new FileInputStream(file).getChannel();
        Logger.debug("开始传输文件");
        int length;
        long progress = 0;
        ByteBuffer buffer2 = ByteBuffer.allocate(1024);
        while ((length = fileChannel.read(buffer2)) > 0) {
            buffer2.flip();
            socketChannel.write(buffer2);
            buffer2.clear();
            progress += length;
            Logger.debug("| " + (100 * progress / file.length()) + "% |");
        }

        if (length == -1) {
            IOUtil.closeQuietly(fileChannel);
            socketChannel.shutdownOutput();
            IOUtil.closeQuietly(socketChannel);
        }
        Logger.debug("======== 文件传输成功 ========");
    }

}
